package ran.quzitech.rnutils.http;

import android.content.Context;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import java.io.File;
import java.util.Map;


import cz.msebera.android.httpclient.Header;
import cz.msebera.android.httpclient.HttpEntity;
import cz.msebera.android.httpclient.entity.ContentType;
import cz.msebera.android.httpclient.entity.StringEntity;
import ran.quzitech.rnutils.utils.StringUtil;

/**
 * Created by ran on 2016/9/8.
 */
public class Request implements IRequest {

    private static Request instance;
    private String time_out;
    private final String TAG = "Request";

    private static final int OK_CODE = 0;
    private AsyncHttpClient client;
    private Context ctx;

    private Request(Context context) {
        // time_out = context.getResources().getString(R.string.time_out);
        ctx = context;
        time_out = "访问超时";
        client = new AsyncHttpClient();
        client.setTimeout(10 * 1000);
    }

    public static Request getInstance(Context context) {
        if (instance == null) {
            instance = new Request(context);
        }
        return instance;
    }

    /**
     * 成功返回，返回Boolean
     *
     * @param handler
     * @param content
     */
    protected void successAction_boolean(IHandler<Boolean> handler,
                                         String content) {

        Log.v(TAG, content);
        content = content.trim().substring(1, content.length() - 1);
        Log.v(TAG, "content trim and without first and last=" + "\n" + content);
        String compresscontent = content.replace("\\n", "").replace("\\", "");
        Log.v(TAG, "content format=" + compresscontent);


        Map map = (Map) JSON.parseObject(compresscontent);
        Log.v(TAG, "map=" + map.toString());


//        try {
//            Log.v(TAG, "parse compress content,cast to map");
//            Map map = (Map) JSON.parse(compresscontent);
//            Log.v(TAG, "map=" + map.toString());
//        } catch (Throwable e) {
//            e.printStackTrace();
//        }
//
//        try {
//            Log.v(TAG, "parseobject compress content,parse to basemodel");
//            BaseModel baseModel = JSON.parseObject(compresscontent, BaseModel.class);
//            Log.v(TAG, "baseModel=" + baseModel.toString());
//        } catch (Throwable e) {
//            e.printStackTrace();
//        }

        if ((int) (map.get("code")) == OK_CODE) {
            // 成功
            handler.getResponse(
                    true,
                    true,
                    new ResponseMessage((int) (map.get("code")), StringUtil
                            .unicode2String((String) (map.get("message")))), content);
        } else {
            handler.getResponse(
                    true,
                    false,
                    new ResponseMessage((int) (map.get("code")), StringUtil
                            .unicode2String((String) (map.get("message")))), content);
        }
    }

    /**
     * 失败返回
     *
     * @param handler
     * @param error
     * @param content
     */
    protected void failureAction(IHandler<?> handler, Throwable error,
                                 String content) {
        Log.v(TAG, error.getMessage() + "  " + content);
        handler.getResponse(false, null, new ResponseMessage(10000, time_out), content);
    }


    @Override
    public void post(String url, String json, IHandler<Boolean> handler) {
        requestWith(url, json, handler);
    }

    @Override
    public void get(String url, final IHandler<Boolean> handler) {
        client.get(ctx, url, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                try {
                    successAction_boolean(handler, new String(responseBody, "utf-8"));
                } catch (Throwable e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                try {
                    failureAction(handler, error, new String(responseBody, "utf-8"));
                } catch (Throwable e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public void patch(String url, String json, final IHandler<Boolean> handler) {
        HttpEntity httpEntity = new StringEntity(json, ContentType.APPLICATION_JSON);
        //  StringEntity stringEntity=new StringEntity(parsms,ContentType.APPLICATION_JSON);
        client.patch(ctx, url, httpEntity, "application/json", new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                try {
                    successAction_boolean(handler, new String(responseBody, "utf-8"));
                } catch (Throwable e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                try {
                    failureAction(handler, error, new String(responseBody, "utf-8"));
                } catch (Throwable e) {
                    e.printStackTrace();
                }
            }
        });
    }


    @Override
    public void requestWith(String url, String parsms, final IHandler<Boolean> handler) {
        HttpEntity httpEntity = new StringEntity(parsms, ContentType.APPLICATION_JSON);
        //  StringEntity stringEntity=new StringEntity(parsms,ContentType.APPLICATION_JSON);
        client.post(ctx, url, httpEntity, "application/json", new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                try {
                    successAction_boolean(handler, new String(responseBody, "utf-8"));
                } catch (Throwable e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                try {
                    failureAction(handler, error, new String(responseBody, "utf-8"));
                } catch (Throwable e) {
                    e.printStackTrace();
                }
            }

        });
    }

    @Override
    public void uploadWith(String url, String params, String filePath, final IHandler<Boolean> handler) {
        //  HttpEntity httpEntity = new StringEntity(params, ContentType.APPLICATION_JSON);
        Map<String, String> map = (Map<String, String>) (JSON.parse(params));
        filePath = filePath.replace("file:", "");
        RequestParams requestParams = new RequestParams(map);
        try {
            requestParams.put("icon", new File(filePath));
        } catch (Throwable e) {
            e.printStackTrace();
        }
        client.post(ctx, url, requestParams, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                try {
                    successAction_boolean(handler, new String(responseBody, "utf-8"));
                } catch (Throwable e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                try {
                    failureAction(handler, error, new String(responseBody, "utf-8"));
                } catch (Throwable e) {
                    e.printStackTrace();
                }
            }
        });

    }


}

